/**
 * 礼物组件
 * page礼物组件
 */
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/live/giftBox.dart';
import 'package:qgchat/common/action/filter/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/giftlistModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:cached_network_image/cached_network_image.dart';

class GiftBox extends StatelessWidget {
  GiftBox({this.token, this.vid, this.canShowSvga = false, Key key})
      : super(key: key);

  final String token;
  final int vid;
  final bool canShowSvga;
  final GiftBoxBloc bloc = GiftBoxBloc();

  @override
  Widget build(BuildContext context) {
    double h = state(context, 'user').info.memberType == 1 ? px(500) : px(600);

    return BlocProvider(
      bloc: bloc,
      child: Container(
        width: w100(context),
        height: h,
        decoration: BoxDecoration(
          color: col("2b2849"),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(px(24)),
            topRight: Radius.circular(px(24)),
          ),
        ),
        child: Column(
          children: <Widget>[
            // 顶部按钮
            headBtnHandle(context),
            // 礼物轮播
            swiperHandle(context),
            // 送出礼物
            sendGiftHandle(context, token),
          ],
        ),
      ),
    );
  }

  // 顶部按钮
  Widget headBtnHandle(context) {
    // 主播的样式和非主播样式
    Widget anchorStyle() {
      return stateBuilder(context, 'user', (UserState user) {
        if (user.info.memberType == 1) {
          return Container(
            margin: EdgeInsets.only(left: px(30)),
            child: Text(
              "查看礼物",
              style: TextStyle(
                color: Colors.white,
                fontSize: px(28),
              ),
            ),
          );
        } else {
          return Container();
        }
      });
    }

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          anchorStyle(),
          Container(
            width: px(128),
            height: px(92),
            child: FlatButton(
              onPressed: () {
                // 关闭方法
                Navigator.pop(context);
              },
              padding: EdgeInsets.all(px(0)),
              child: Text(
                "取消",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(34),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 生成轮播
  Widget swiperHandle(context) {
    // 选中礼物的样式
    BoxDecoration checkStyle(isCheck) {
      if (isCheck) {
        return BoxDecoration(
          borderRadius: BorderRadius.circular(px(7)),
          gradient: LinearGradient(
            colors: [col("c571f5"), col("fa71cd")],
            begin: FractionalOffset(1, 0),
            end: FractionalOffset(1, 1),
          ),
        );
      } else {
        return BoxDecoration(
          borderRadius: BorderRadius.circular(px(7)),
          color: col("2b2849"),
        );
      }
    }

    // 单个礼物
    Widget gift(GiftlistModel giftItem, int g, int i) {
      return StreamBuilder(
        stream: bloc.choiceStream,
        initialData: bloc.choice,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          ChoiceGift now = snapshot.data;
          return Container(
            width: px(172),
            height: px(172),
            padding: EdgeInsets.all(px(4)),
            decoration: checkStyle(g == now.group && i == now.unit),
            child: FlatButton(
              onPressed: () => bloc.choiceGift(g, i),
              padding: EdgeInsets.zero,
              child: Container(
                width: flex1,
                decoration: BoxDecoration(
                  color: col("2b2849"),
                  borderRadius: BorderRadius.circular(px(7)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    // 礼物图
                    Container(
                      width: px(70),
                      height: px(70),
                      decoration: BoxDecoration(
                        color: col("f8f8f8"),
                        borderRadius: BorderRadius.circular(px(10)),
                      ),
                      child: Stack(
                        overflow: Overflow.visible,
                        alignment: Alignment.center,
                        children: <Widget>[
                          Container(
                            width: px(42),
                            height: px(42),
                            // padding: EdgeInsets.all(px(14)),
                            child: CachedNetworkImage(
                              imageUrl: "${giftItem.giftIcon}",
                              fit: BoxFit.cover,
                              errorWidget: (context, url, error) {
                                return Image.asset(
                                  "assets/images/icon/giftbg.png",
                                );
                              },
                            ),
                          ),
                          stateBuilder(context, 'user', (UserState user) {
                            num count = giftItem.count ?? 0;
                            if (user.info.memberType == 1 && count > 0) {
                              return Positioned(
                                top: -px(18),
                                right: -px(18),
                                child: Container(
                                  height: px(36),
                                  padding:
                                      EdgeInsets.symmetric(horizontal: px(11)),
                                  decoration: BoxDecoration(
                                    color: col("ffb240"),
                                    borderRadius: BorderRadius.circular(px(18)),
                                  ),
                                  child: Text(
                                    "${Filter.maxToAdd(count, 99)}",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: px(26),
                                    ),
                                  ),
                                ),
                              );
                            } else {
                              return Container();
                            }
                          }),
                        ],
                      ),
                    ),
                    // 礼物名
                    Container(
                      margin: EdgeInsets.only(top: px(15)),
                      child: Text(
                        "${giftItem.giftName}",
                        style: TextStyle(
                          height: .95,
                          color: Colors.white,
                          fontSize: px(24),
                        ),
                      ),
                    ),
                    // 金币
                    Container(
                      margin: EdgeInsets.only(top: px(5)),
                      child: Text(
                        "${giftItem.giftGold}金币",
                        style: TextStyle(
                          height: .95,
                          color: col("9594a4"),
                          fontSize: px(20),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      );
    }

    return StreamBuilder(
      stream: bloc.giftStream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          List<List<GiftlistModel>> list = snapshot.data;

          return Container(
            width: w100(context),
            height: px(390),
            padding: EdgeInsets.symmetric(horizontal: px(30)),
            child: Swiper(
              onTap: (int index) {},
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  padding: EdgeInsets.only(bottom: px(46)),
                  child: Wrap(
                    children: list[index].asMap().keys.map((int i) {
                      return gift(list[index][i], index, i);
                    }).toList(),
                  ),
                );
              },
              pagination: SwiperPagination(
                builder: MyRectSwiperPaginationBuilder(
                  color: col("6b6980"),
                  activeColor: Colors.white,
                  size: px(20),
                  activeSize: px(20),
                ),
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }

  // 送礼物相应功能按钮
  Widget sendGiftHandle(BuildContext context, String token) {
    return stateBuilder(context, 'user', (UserState user) {
      if (user.info.memberType == 1) {
        return Container();
      } else {
        return Container(
          height: px(60),
          padding: EdgeInsets.symmetric(horizontal: px(30)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              // 充值
              Container(
                child: Row(
                  children: <Widget>[
                    Image.asset(
                      "assets/images/icon/star.png",
                      width: px(32),
                      height: px(32),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: px(15)),
                      child: StreamBuilder(
                        stream: bloc.giftPriceStream,
                        initialData: 0,
                        builder: (
                          BuildContext context,
                          AsyncSnapshot snapshot,
                        ) {
                          return Text(
                            "${snapshot.data}",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(28),
                            ),
                          );
                        },
                      ),
                    ),
                    Container(
                      width: px(155),
                      child: FlatButton(
                        onPressed: () => goPage(context, '/recharge'),
                        padding: EdgeInsets.all(0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              "充值",
                              style: TextStyle(
                                color: col("ffe334"),
                                fontSize: px(26),
                              ),
                            ),
                            Container(
                              child: Icon(
                                Icons.keyboard_arrow_right,
                                color: col("ffe334"),
                                size: px(44),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              // 送礼物
              Container(
                child: Row(
                  children: <Widget>[
                    // 选择数量
                    Container(
                      height: px(52),
                      margin: EdgeInsets.only(right: px(20)),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(px(8)),
                      ),
                      child: Row(
                        children: <Widget>[
                          Container(
                            width: px(60),
                            child: FlatButton(
                              onPressed: () => bloc.choiceGiftCount(false),
                              padding: EdgeInsets.all(0),
                              child: Icon(
                                Icons.remove,
                                color: col("303133"),
                                size: px(44),
                              ),
                            ),
                          ),
                          Container(
                            width: px(70),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border(
                                left: BorderSide(
                                  color: col("edeff2"),
                                  width: 1,
                                ),
                                right: BorderSide(
                                  color: col("edeff2"),
                                  width: 1,
                                ),
                              ),
                            ),
                            child: StreamBuilder(
                              stream: bloc.giftCountStream,
                              initialData: 1,
                              builder: (
                                BuildContext context,
                                AsyncSnapshot snapshot,
                              ) {
                                return Text(
                                  "${snapshot.data}",
                                  style: TextStyle(
                                    color: col("303133"),
                                    fontSize: px(28),
                                  ),
                                );
                              },
                            ),
                          ),
                          Container(
                            width: px(60),
                            child: FlatButton(
                              onPressed: () => bloc.choiceGiftCount(true),
                              padding: EdgeInsets.all(0),
                              child: Icon(
                                Icons.add,
                                color: col("303133"),
                                size: px(44),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 送出按钮
                    Container(
                      width: px(120),
                      height: px(60),
                      child: FlatButton(
                        onPressed: () {
                          bloc.givingGifts(context, token,
                              vid: vid, canShowSvga: canShowSvga);
                        },
                        color: col("ffcd35"),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(
                            sp(30),
                          ),
                        ),
                        child: Text(
                          "送出",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: px(26),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      }
    });
  }
}

// 轮播矩形分页器
class MyRectSwiperPaginationBuilder extends SwiperPlugin {
  ///color when current index,if set null , will be Theme.of(context).primaryColor
  final Color activeColor;

  ///,if set null , will be Theme.of(context).scaffoldBackgroundColor
  final Color color;

  ///Size of the dot when activate
  final double activeSize;

  ///Size of the dot
  final double size;

  /// Space between dots
  final double space;

  final Key key;

  const MyRectSwiperPaginationBuilder(
      {this.activeColor,
      this.color,
      this.key,
      this.size: 10.0,
      this.activeSize: 10.0,
      this.space: 3.0});

  @override
  Widget build(BuildContext context, SwiperPluginConfig config) {
    if (config.itemCount > 20) {
      print(
          "The itemCount is too big, we suggest use FractionPaginationBuilder instead of DotSwiperPaginationBuilder in this sitituation");
    }
    Color activeColor = this.activeColor;
    Color color = this.color;

    if (activeColor == null || color == null) {
      ThemeData themeData = Theme.of(context);
      activeColor = this.activeColor ?? themeData.primaryColor;
      color = this.color ?? themeData.scaffoldBackgroundColor;
    }

    List<Widget> list = [];

    int itemCount = config.itemCount;
    int activeIndex = config.activeIndex;

    for (int i = 0; i < itemCount; ++i) {
      bool active = i == activeIndex;
      list.add(Container(
        key: Key("pagination_$i"),
        margin: EdgeInsets.all(space),
        child: Container(
          color: active ? activeColor : color,
          width: active ? activeSize : size,
          height: px(4),
        ),
      ));
    }

    if (config.scrollDirection == Axis.vertical) {
      return new Column(
        key: key,
        mainAxisSize: MainAxisSize.min,
        children: list,
      );
    } else {
      return new Row(
        key: key,
        mainAxisSize: MainAxisSize.min,
        children: list,
      );
    }
  }
}
